; Source of this file: http://www.autoitscript.com/forum/topic/114540-switch-focus-to-window-with-process-name/
#include <array.au3>
;$iPid = Run("msaccess.exe")
;Sleep(100) ; allow notepad to create window
;$aArray = _WinGetInfoByProcess("msaccess.exe", 1)
;_ArrayDisplay($aArray, "by Name, only visible windows")

Func _WinGetInfoByProcess($vProcess, $nShow = 2)
	;
	;===============================================================================
	;
	; Function Name:	_WinGetInfoByProcess
	; Description::	 Get Window Handle of Process
	; Parameter(s):	 $vProcess = Processname(e.g. "Notepad.exe") or Processnumber(e.g. 4711 )
	;				   $nShow = -1 "All (Visble or not)"
	;				   $nShow = 0 "Not Visible Only"
	;				   $nShow = 1 "Visible Only"
	;				   $nShow = 2 "Return handle of newest  window " (Default)
	; Requirement(s):   none
	; Return Value(s):
	;				   @extended = returns number of entries in the array
	;				   @error = 0 AND $nShow = 2 (default)  returns handle of newest window
	;				   @error = 0 returns array with processinfos
	;							  n = 1 to @extended
	;							  Array[n][0] shows windows title.
	;							  Array[n][1] shows windows handle.
	;							  Array[n][2] shows windows Pid.
	;				   @error = 1 Process not found.
	;				   @error = 2 Window not found.
	; Author(s):		inspired by Smoke_N's script _WinGetHandleByPID()
	;				   but to handle more than one process with the same name
	;				   and to return handle of newest window ($nShow = 2).
	; tested versions:  Autoit 3.3.0.0 
	;
	;===============================================================================
	;
	If Not ProcessExists($vProcess) Then Return SetError(1, 0, 0) ; no matching process
	Local $iWinList, $aWinList = WinList()
	Local $iResult, $aResult[UBound($aWinList)][3]
	Local $iProcessList, $aProcessList = ProcessList($vProcess)
	If $aProcessList[0][0] = 0 Then Local $aProcessList[2][2] = [[1, 0],["", $vProcess]]
	For $iWinList = 1 To $aWinList[0][0]
		For $iProcessList = 1 To $aProcessList[0][0]
			If WinGetProcess($aWinList[$iWinList][1]) = $aProcessList[$iProcessList][1] Then
				If $nShow > -1 And Not $nShow = (2 = BitAND(WinGetState($aWinList[$iWinList][1]), 2)) Then ContinueLoop
				$iResult += 1
				$aResult[$iResult][0] = $aWinList[$iWinList][0]
				$aResult[$iResult][1] = $aWinList[$iWinList][1]
				$aResult[$iResult][2] = $aProcessList[$iProcessList][1]
			EndIf
		Next
	Next
	If $iResult = 0 Then Return SetError(2, 0, 0) ; no window found
	ReDim $aResult[$iResult + 1][3]
	$aResult[0][0] = $iResult
	If $nShow = 2 Then Return SetError(0, $iResult, $aResult[1][1])
	Return SetError(0, $iResult, $aResult)
EndFunc   ;==>_WinGetInfoByProcess